<template>
  <div class="app-container">
    <el-tabs v-model="currTab" type="border-card" @tab-change="currTabChange">
      <el-tab-pane label="考勤设备" name="device">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="请输入关键字"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="设备分类" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择设备分类" filterable clearable>
                <el-option
                  v-for="item in checkindeviceType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="进/出口" prop="inOut">
              <el-select v-model="queryParams.inOut" placeholder="请选择进/出口" filterable clearable>
                <el-option label="进口" value="1"></el-option>
                <el-option label="出口" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button-group style="margin-left: 12px">
                  <el-button type="primary" :disabled="selectRow.length < 1" @click="toIssueCommand">
                    <i-ep-finished />
                    下发命令
                  </el-button>
                  <el-button ref="popoBtnRef" type="primary" :disabled="selectRow.length < 1" @click="toPopo">
                    <el-icon v-if="!popoVisibled">
                      <ArrowDownBold />
                    </el-icon>
                    <el-icon v-else>
                      <ArrowUpBold />
                    </el-icon>
                  </el-button>
                  <el-popover
                    ref="popoverRef"
                    v-model="popoVisibled"
                    :virtual-ref="popoBtnRef"
                    trigger="click"
                    virtual-triggering
                    width="300"
                    @show="popoShow"
                    @hide="popoHide"
                  >
                    <el-checkbox-group
                      v-model="commandCheckList"
                      v-loading="commandPDLoading"
                      style="width: 100%"
                      @change="handleCheckboxChange"
                    >
                      <el-checkbox
                        v-for="item in commandPulldownList"
                        :key="item.value"
                        border
                        :label="item.label"
                        style="width: 100%; margin-bottom: 5px"
                      ></el-checkbox>
                    </el-checkbox-group>
                  </el-popover>
                </el-button-group>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="tableList"
            highlight-current-row
            size="small"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" min-width="40" align="center"></el-table-column>
            <el-table-column label="序号" type="index" min-width="50" align="center"></el-table-column>
            <el-table-column key="name" label="设备名称" align="center" prop="name" min-width="150">
              <template #default="scope">
                <el-tooltip
                  effect="light"
                  :content="'code:' + scope.row.code + '  ip:' + scope.row.ipAddress"
                  placement="top"
                >
                  <span style="cursor: pointer"> {{ scope.row.name }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column key="corpName" label="所属企业" prop="corpName" min-width="200s" />
            <el-table-column key="projectName" label="所属项目" prop="projectName" min-width="200" />
            <el-table-column key="code" label="设备序列号" align="center" min-width="150" prop="code">
            </el-table-column>
            <el-table-column key="typeName" label="设备类别" align="center" prop="typeName" min-width="80" />
            <el-table-column key="startDate" label="有效起始日期" min-width="100" align="center" prop="startDate" />
            <el-table-column key="endDate" label="有效截至日期" min-width="100" align="center" prop="endDate" />
            <el-table-column key="isOnline" label="在线/离线" align="center" prop="isOnline" min-width="75">
              <template #default="scope">
                <el-tag :type="scope.row.isOnline ? '' : 'danger'">{{ scope.row.isOnline ? "在线" : "离线" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column key="isDisable" label="是否禁用" align="center" min-width="70" prop="isDisable">
              <template #default="scope">
                <el-tag :type="scope.row.isDisable ? 'danger' : 'success'">{{
                  scope.row.isDisable ? "禁用" : "启用"
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column key="inOutName" label="设备进/出口" min-width="90" align="center" prop="inOutName" />
            <!-- <el-table-column key="model" label="设备型号" min-width="160" align="center" prop="model" /> -->
            <!-- <el-table-column key="version" label="设备版本" min-width="160" align="center" prop="version" />
            <el-table-column key="ipAddress" label="ip地址" min-width="100" align="center" prop="ipAddress" /> -->
            <el-table-column
              key="lastSyncTime"
              label="最后同步时间"
              min-width="140"
              align="center"
              prop="lastSyncTime"
            />
            <el-table-column key="remark" label="备注" min-width="160" align="center" prop="remark" />
            <!-- <el-table-column key="createTime" label="创建时间" min-width="140" align="center" prop="createTime" /> -->
            <el-table-column label="操作" fixed="right" :width="130">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="openDetail(scope.row.id, '详情')"> 详情 </el-button>
                <el-button type="success" link size="small" @click="openHistory(scope.row.code)"> 下发记录 </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="APP授权" name="app">
        <!-- <div class="search-container">
          <el-form ref="queryAppDeviceFormRef" :model="queryAppDeviceForm" :inline="true">
            <el-form-item prop="keywords">
              <el-input
                v-model="queryAppDeviceForm.keywords"
                placeholder="请输入关键字"
                clearable
                style="width: 200px"
              />
              <el-button type="primary" style="margin-left: 0; border-radius: 0" @click="handleAppDeviceQuery">
                搜索
              </el-button>
              <el-button @click="resetAppDeviceQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div> -->
        <div class="table-container">
          <el-row :gutter="20">
            <el-col :span="24" :offset="0" style="margin-top: 10px">
              <el-table
                ref="appDeviceTableRef"
                v-loading="loading"
                :data="appDeviceData"
                style="width: 100%"
                :show-overflow-tooltip="{ effect: 'light' }"
              >
                <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
                <el-table-column label="所属项目" prop="projectName" min-width="250" />
                <el-table-column label="所属企业" prop="corpName" min-width="200" />
                <el-table-column label="状态" prop="isDisable" min-width="80">
                  <template #default="scope">
                    <span v-if="scope.row.isDisable">
                      <el-text type="warning"> 禁用</el-text>
                    </span>
                    <span v-else>
                      <el-text type="success"> 启用 </el-text>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="开始日期" prop="startDate" min-width="100" />
                <el-table-column label="结束日期" prop="endDate" min-width="80" />
                <el-table-column
                  v-if="userType != 2 && userType != 5"
                  label="创建时间"
                  prop="createTime"
                  min-width="200"
                />
                <el-table-column
                  v-if="userType != 2 && userType != 5"
                  label="最后修改时间"
                  prop="lastUpdateTime"
                  min-width="120"
                />
              </el-table>
              <pagination
                v-if="total > 0"
                v-model:total="appDevicePagination.total"
                v-model:page="appDevicePagination.pageNum"
                v-model:limit="appDevicePagination.pageSize"
                @pagination="handleAppDeviceQuery"
              />
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <detail-description
      v-if="dialogDetail.visible"
      :dialog-detail="dialogDetail"
      class="system"
      :style="{ '--mobileAddFormHeight': mobile === 'mobile' ? screenHeight - 117 + 'px' : 'auto' }"
      @send-detail-close="sendDetailClose"
    ></detail-description>

    <CommandHistory
      v-if="dialogHistory.visible"
      :dialog-history="dialogHistory"
      class="system"
      :style="{ '--mobileAddFormHeight': mobile === 'mobile' ? screenHeight - 100 + 'px' : 'auto' }"
      @send-history-close="sendHistoryClose"
    ></CommandHistory>
  </div>
</template>

<script lang="ts" setup>
import DetailDescription from "./detail.vue";
import CommandHistory from "./commandHistory.vue";
import { DeviceListType } from "@/api/system/device/types";
import { getCheckInDeviceList, issueCommand } from "@/api/system/device/index";
import { QueryAppCheckinAuthList } from "@/api/device/index";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { useUserStoreHook } from "@/store/modules/user";

const screenStore = useScreen();
const userStore = useUserStoreHook();
const mobile = computed(() => screenStore.device);
const screenHeight = computed(() => screenStore.screenHeight);
const userType = computed(() => userStore.type);

function initScreen() {}

/*分页列表查询*/
const total = ref(0);
const loading = ref(false);
const queryFormRef = ref(ElForm);
const tableList = ref<DeviceListType[]>();
const currTab = ref<String>("device");
/* 下发命令 */
const popoVisibled = ref(false);
const popoBtnRef = ref();
const popoverRef = ref();
const commandPulldownList = ref<any[]>([]);
const commandCheckList = ref([]);
const commandPDLoading = ref(false);
const selectRow = ref<any[]>([]);
const selectCommmand = ref<any[]>([]);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 20,
});

const dialogDetail = reactive({
  visible: false,
  id: 0,
  title: "设备详情",
  footBtn: "",
  detail: "详情",
});

const dialogHistory = reactive({
  visible: false,
  code: 0,
  title: "命令下发记录",
  footBtn: "",
  detail: "记录",
});
/* 列表查询 */
async function handleQuery() {
  loading.value = true;
  let list = await getCheckInDeviceList(queryParams);
  loading.value = false;
  if (list.type === 0) {
    if (list.success) {
      tableList.value = list.data.list;
      queryParams.pageNum = list.data.pageNum;
      queryParams.pageSize = list.data.pageSize;
      total.value = list.data.total;
    } else {
      ElMessage.error(list.msg);
    }
  } else {
    ElMessage.error(list.msg);
  }
}

const handleSelectionChange = (selection: any) => {
  selectRow.value = [];
  selection.map((item: any) => selectRow.value.push(item.id));
};

const handleCheckboxChange = (selection: any[]) => {
  let temp;
  selectCommmand.value = [];
  selection.map((item: any) => {
    temp = commandPulldownListFilter(item);
    if (temp) {
      selectCommmand.value.push(temp);
    }
  });
};

function commandPulldownListFilter(val: any) {
  let temp;
  if (val) {
    temp = commandPulldownList.value.filter((i) => i.label === val);
    if (temp && temp.length > 0) {
      return temp[0].value;
    } else {
      return "";
    }
  }
}

function toIssueCommand() {
  if (selectRow.value && selectRow.value.length < 1) {
    ElMessage.warning("请选择命令下发机器!");
    return;
  }
  if (selectCommmand.value && selectCommmand.value.length < 1) {
    ElMessage.warning("请选择下发命令!");
    return;
  }
  issueCommand(selectRow.value.toString(), selectCommmand.value.toString())
    .then((data) => {
      if (data.success) {
        ElMessage.success(data.msg);
      } else {
      }
    })
    .catch(() => {
      commandCheckList.value = [];
      selectCommmand.value = [];
    });
}

function toPopo() {
  popoVisibled.value = !popoVisibled.value;
}

function popoShow() {
  commandPDLoading.value = false;
  commandPulldownList.value = getDicts("checkInCommandType"); //下发命令
  popoVisibled.value = true;
}

function popoHide() {
  commandCheckList.value = [];
  selectCommmand.value = [];
  popoVisibled.value = false;
}

function openDetail(id: any, detail: any) {
  dialogDetail.title = "考勤设备详情";
  dialogDetail.footBtn = "";
  dialogDetail.id = id;
  dialogDetail.detail = detail;
  dialogDetail.visible = true;
}

function openHistory(code: any) {
  dialogHistory.title = "命令下发记录";
  dialogHistory.code = code;
  dialogHistory.visible = true;
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  handleQuery();
}

/* 关闭弹窗并刷新列表 */

function sendDetailClose() {
  dialogDetail.visible = false;
}

function sendHistoryClose() {
  dialogHistory.visible = false;
}
/** app设备授权 */

const queryAppDeviceFormRef = ref(ElForm);
const appDeviceData = ref<Array<any>>([]);
const queryAppDeviceForm = reactive({
  keywords: "",
});
const appDevicePagination = reactive({
  pageNum: 0,
  pageSize: 20,
  total: 0,
});
const handleAppDeviceQuery = function () {
  loading.value = true;
  const reqData = {
    pageNum: appDevicePagination.pageNum,
    pageSize: appDevicePagination.pageSize,
    ...queryAppDeviceForm,
  };
  QueryAppCheckinAuthList(reqData)
    .then((res) => {
      if (res.type === 0) {
        if (res.success) {
          appDeviceData.value = res.data.list;
          appDevicePagination.pageNum = res.data.pageNum;
          appDevicePagination.pageSize = res.data.pageSize;
          appDevicePagination.total = res.data.total;
        } else {
          ElMessage.error(res.msg);
        }
      } else {
        ElMessage.error(res.msg);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
function resetAppDeviceQuery() {
  queryAppDeviceFormRef.value.resetFields();
  appDevicePagination.pageNum = 1;
  handleAppDeviceQuery();
}
const currTabChange = (t: string) => {
  if (t == "device") {
    queryParams.pageNum = 1;
    handleQuery();
  } else if (t == "app") {
    appDevicePagination.pageNum = 1;
    handleAppDeviceQuery();
  }
};
onMounted(() => {
  initScreen();
  handleQuery();
});
const checkindeviceType = getDicts("deviceProvider"); //设备类别
</script>

<style lang="less" scoped>
:deep(.el-divider--vertical) {
  border-left-color: black;
}

.header {
  font-size: 18px;
  font-weight: 700;
}
</style>
